package com.haliyoo.adhere.activity;

import java.util.Timer;
import java.util.TimerTask;

import com.haliyoo.adhere.R;
import com.haliyoo.adhere.bean.UserBean;
import com.haliyoo.adhere.bean.WeiboBean;
import com.haliyoo.adhere.controller.AdUserConstant;
import com.haliyoo.adhere.controller.Constants;
import com.haliyoo.adhere.controller.OAuthConstant;
import com.haliyoo.adhere.handler.CreativeHallHandler;
import com.haliyoo.adhere.handler.DraftsHandler;
import com.haliyoo.adhere.handler.InviteFriendsHandler;
import com.haliyoo.adhere.handler.MoreHandler;
import com.haliyoo.adhere.handler.MyCharmHandler;
import com.haliyoo.adhere.http.AdClient;
import com.haliyoo.adhere.sqlite.DataHelper4User;
import com.haliyoo.adhere.util.BitmapGet;
import com.haliyoo.adhere.widget.DialogListener;
import com.haliyoo.adhere.widget.PromptDialog;

import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class HallActivity extends Activity implements OnClickListener, DialogListener{
	private static String TAG = "HallActivtiy";
	/**
	 * 大厅页面中的User是当前用户
	 */
	private static User user = null;
	public static Weibo weibo = null;
	Timer tr = null;
	private Handler process = new WeiboProc(this);
	static int idx = 0; 
	private GetUserThread getUserThread = null;
	private ShowUserHandler showUserHandler = new ShowUserHandler();
	private RadioGroup rgMain = null;
	private static int checkedId = 0;
	
	public void onCreate(Bundle savedInstanceState) {
    	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hall);
		
		/**
		 * 状态栏单选框功能
		 */
		rgMain = (RadioGroup) findViewById(R.id.main_radio);
		rgMain.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				HallActivity.checkedId = checkedId;
				
				switch (checkedId) {
				case R.id.radio_hall:
					hallHandler();
					break;

				case R.id.radio_charm:
					charmHandler();
					break;

				case R.id.radio_drafts:
					draftsHandler();
					break;

				case R.id.radio_invite:
					inviteHandler();
					break;

				case R.id.radio_more:
					moreHandler();
					break;
				}
			}
		});

//		RadioButton rbCharm = (RadioButton) findViewById(R.id.radio_charm);
//		rbCharm.setChecked(true);
		
		Intent intent = getIntent();
		
		Bundle bundle = intent.getExtras();
		AccessToken accessToken = null;

		/**
		 * 判断能否获取到bundle，如果获取不到则通过请求获取accessToken
		 * 否则，直接提取accessToken
		 */
		if (bundle == null){
			Uri uri = this.getIntent().getData();
			RequestToken requestToken = OAuthConstant.getInstance().getRequestToken();
			try {
				accessToken = requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));
				UserBean user = LoginActivity.getUser();
				
				/// 保存数据库
				user.setUserId(accessToken.getUserId());
				user.setToken(accessToken.getToken());
				user.setTokenSecret(accessToken.getTokenSecret());
		    	DataHelper4User dbHelper = new DataHelper4User(this);
		        dbHelper.insert(user);
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			accessToken = (AccessToken) bundle.getSerializable("accesToken");
		}
		
		/**
		 * 开启线程获取用户信息
		 */
//		if (getUserThread == null) {
//			getUserThread = new GetUserThread(accessToken);
//		}
//		getUserThread.start();
		/// 这里不能使用线程，原因：
		/// 如果使用线程获取微博信息，可能会比获取微博列表慢，造成无法获取列表而异常
		if (accessToken != null) {
			
			try {
				OAuthConstant.getInstance().setAccessToken(accessToken);
				weibo = OAuthConstant.getInstance().getWeibo();
				
				weibo.setToken(OAuthConstant.getInstance().getToken(), OAuthConstant.getInstance().getTokenSecret());
				
				user = weibo.showUser(accessToken.getUserId() + "");
									Log.i(TAG, "user:" + user.toString());
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		} else {
			return;
		}
		
		/**
		 * 显示默认项
		 */
		RadioButton rbHall = (RadioButton) findViewById(R.id.radio_hall);
		rbHall.setChecked(true);
		
		/**
		 * 和AdHere服务器通讯
		 */
		getAdHereData();
	}

	/*
	 * 获取AdHere数据
	 */
	void getAdHereData() {

    	/// 开启线程链接AdHere服务器
    	new Thread() {
    		
            @Override
            public void run() {
            	UserBean user = LoginActivity.getUser();
            	final String userId = new Long(user.getUserId()).toString();
            	
//            	/// 循环登录，直到登录成功为止
//            	if (AdUserConstant.getInstance().login(userId, "") != 1) {
//            		Log.i(TAG, "login failed, return.");
//            		return;
//            	}
            	
        		/// 登录成功
            	AdUserConstant.getInstance().user = userId;
            	HallActivity.idx = 0;
        		
        		/// 开启定时器来转发微博
            	tr = new Timer();  
                tr.schedule(new TimerTask(){
  
                	@Override  
	                public void run() {  
                		/// 转发列表存在则转发
                		if (AdUserConstant.getInstance().repostList != null) {
                        	process.sendEmptyMessage(HallActivity.idx);  
                			HallActivity.idx++;  
                			
                			if (HallActivity.idx >= AdUserConstant.getInstance().repostList.size()) {
                				return;
                			}
                		}
                		/// 转发列表不存在则获取
                		else {
                    		/// 获取广告列表，直到获取成功未知
                    		AdUserConstant.getInstance().list(AdUserConstant.getInstance().user, 
                    				AdUserConstant.getInstance().sign);
                    		
                    		HallActivity.idx = 0;
                		}
	                } 
                }, 1000, 300000);
            }
        }.start();
	}
	
	//完全退出应用
	public void exit(){
		
//		1.5 - 2.1之前下面两行是ok的,2.2之后就不行了，所以不通用
//		ActivityManager am = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
//		am.restartPackage("com.tutor.exit");
		
		Intent intent = new Intent();
		intent.setClass(HallActivity.this, LoginActivity.class);
		//这里设置flag还是比较 重要的
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		//发出退出程序指示
		intent.putExtra("flag", Constants.EXIT_APPLICATION);
		startActivity(intent);
	}

	@Override
	public void doCancel(int flag) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void doComfirm(int flag) {
		// TODO Auto-generated method stub

		if (flag == 0){
			Log.d(TAG, "finish:------------");

			//exit();
			System.exit(0);
		} else if (flag == 1) {
			Log.d(TAG, "delete:------------");

			DraftsHandler.weiboList.deleteAllWeibo();
		} else if (flag == 2) {
			Log.d(TAG, "off:------------");

			/// 在数据库中删除用户
			UserBean user = LoginActivity.getUser();
			
	    	DataHelper4User dbHelper = new DataHelper4User(this);
	        dbHelper.delete(user);
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			
			finish();
		}
	}
	
	/**
	 * 获取当前用户信息
	 * @return 返回当前用户
	 */
	public static User getUser() {
		return user;
	}
	
	class GetUserThread extends Thread {
		
		AccessToken accessToken = null;
		
		public GetUserThread(AccessToken accessToken) {
			this.accessToken = accessToken;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (accessToken != null) {
			
				try {
					OAuthConstant.getInstance().setAccessToken(accessToken);
					weibo = OAuthConstant.getInstance().getWeibo();
					
					weibo.setToken(OAuthConstant.getInstance().getToken(), OAuthConstant.getInstance().getTokenSecret());
					
					user = weibo.showUser(accessToken.getUserId() + "");
										Log.i(TAG, "user:" + user.toString());
				} catch (WeiboException e) {
					e.printStackTrace();
				}
			}
			
			super.run();
		}
	}
	
	/**
	 * 显示用户处理器
	 * @author Administrator
	 *
	 */
	class ShowUserHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == Constants.SHOW_USER) {
				User user = (User) msg.obj;

				/**
				 * 填写用户资料
				 */
				
				/// 头像
				ImageView ivProfile = (ImageView) findViewById(R.id.IMAGE_VIEW_PROFILE);
				Bitmap bitmap = BitmapGet.getHttpBitmap(user.getProfileImageURL());
				ivProfile.setImageBitmap(bitmap);//设置Bitmap
				
				Log.i(TAG, "image uri:" + user.getProfileImageURL().toString());
				
				/// 用户名
				TextView tvUser = (TextView) findViewById(R.id.TEXT_VIEW_USER);
				tvUser.setText(user.getName());
				
				/// 位置
				TextView tvLocation = (TextView) findViewById(R.id.TEXT_VIEW_LOCATION);
				tvLocation.setText(user.getLocation());
				
				/// 签名
				//TextView tvSignature = (TextView) findViewById(R.id.TEXT_VIEW_SIGNATURE);
				//tvSignature.setText(user.getDescription());
				
				/// 性别
				ImageView ivGender = (ImageView) findViewById(R.id.IMAGE_VIEW_GENDER);
				if (user.getGender().equals("m")){
					ivGender.setImageResource(R.drawable.male);
				}
				else{
					ivGender.setImageResource(R.drawable.female);
				}
			}
			
			super.handleMessage(msg);
		}
		
	}
	
	/**
	 * 大厅的处理
	 */
	void hallHandler() {
		new CreativeHallHandler(this);
	}
	
	/**
	 * 魅力页面的处理
	 */
	void charmHandler() {
		new MyCharmHandler(this).setCharmByUserId(user.getName());
	}
	
	/**
	 * 草稿箱页面的处理
	 */
	void draftsHandler() {
		new DraftsHandler(this);
	}
	
	/**
	 * 邀请朋友页面的处理
	 */
	void inviteHandler() {
		new InviteFriendsHandler(this);
	}
	
	/**
	 * 更多页面的处理
	 */
	void moreHandler() {
        new MoreHandler(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			/// 提示是否退出软件
			PromptDialog.show(HallActivity.this, 
					getString(R.string.STR_EXIT_APP_REQUEST), HallActivity.this, 0, false);
			
			return false;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		//或者下面这种方式
		//android.os.Process.killProcess(android.os.Process.myPid()); 
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		/**
		 * 删除草稿箱
		 */
		case 0:
			PromptDialog.show(HallActivity.this, 
					getString(R.string.STR_DELETE_ALL_DRAFTS), HallActivity.this, 1, false);
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		switch (checkedId) {
		case R.id.radio_hall:
			break;

		case R.id.radio_charm:
			break;

		case R.id.radio_drafts:
			menu.add(0, 0, 0, getString(R.string.STR_DELETE_ALL)).setIcon(R.drawable.delete_all);
			break;

		case R.id.radio_invite:
			break;

		case R.id.radio_more:
			break;
		}
		
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 获取选择的布局编号
	 * @return 整型编号
	 */
	public static int getCheckedId() {
		return checkedId;
	}
}

class WeiboProc extends Handler {  
	  
	private static Activity res;  
	  
	public WeiboProc(Activity aThis) {  
		WeiboProc.res = aThis;  
	} 
	
	public void handleMessage(Message msg) {  
		int size = msg.what;  
		Weibo weibo = HallActivity.weibo;
		
		if (AdUserConstant.getInstance().repostList != null) {
			
    		/// 获取转发id
        	WeiboBean wb = AdUserConstant.getInstance().repostList.get(size);
        	
        	/// 转发到新浪微博上
        	try {
        		String[] repostStrs = {
        				"至于你信不信，反正我信了！",
        				"给力，真给力！！！",
        				"哇，能不能HOLD住啊～～",
        				"不错不错，就你了。",
        				"唉，伤不起啊～",
        				"有一万个理由，我也选你，去。",
        				"哇，好棒哦～",
        				"支持[鼓掌]",
        				"卡哇伊[嘻嘻]",
        				"一定要做具有中国特色的社会主义××",
        				""
        		};
        		int index = (int) (System.currentTimeMillis() % repostStrs.length);
				weibo.repost(new Long(wb.getWeiboId()).toString(), repostStrs[index]);
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (size == AdUserConstant.getInstance().repostList.size() - 1) {
		    	/// 申请微博id集合空间
		    	String[] adIds = new String[AdUserConstant.getInstance().repostList.size()];
		    	for (int index=0; index<AdUserConstant.getInstance().repostList.size(); index++) {
		    		adIds[index] = new Long(AdUserConstant.getInstance().repostList.get(index).getWeiboId()).toString();
		    	}
		    	
		    	/// 如果转发完了，则汇报到AdHere服务器
		    	AdUserConstant.getInstance().repost(AdUserConstant.getInstance().user, 
		    			adIds, AdUserConstant.getInstance().sign);
			}
    	}
	}  
}  